<!-- src/views/system/RoleEdit.vue -->
<script setup>
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoleStore } from '@/stores/RoleStores'
import AclView from "@/components/AclList/AclView.vue"

const roleStore = useRoleStore()

const emit = defineEmits(['update:visible', 'success'])
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  roleData: {
    type: Object,
    default: () => ({})
  }
})

const formRef = ref()
const loading = ref(false)

const form = reactive({
  id: null,
  name: '',
  code: '',
  isDelete: 0,  // 0-正常 1-已删除
  dataScope: null,
  aclIds: [] // 添加权限ID数组
})

const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  dataScope: [
    { required: true, message: '请选择数据权限', trigger: 'change' }
  ],
}

// 监听角色数据变化，填充表单
watch(
    () => props.roleData,
    (newRoleData) => {
      if (newRoleData && Object.keys(newRoleData).length > 0) {
        Object.assign(form, {
          id: newRoleData.id || null,
          name: newRoleData.name || '',
          code: newRoleData.code || '',
          isDelete: newRoleData.isDelete !== undefined ? newRoleData.isDelete : 0,
          dataScope: newRoleData.dataScope !== undefined ? Number(newRoleData.dataScope) : null,
          aclIds: Array.isArray(newRoleData.aclIds) ? [...newRoleData.aclIds] : [] // 确保是数组
        })
      } else {
        // 重置表单
        Object.assign(form, {
          id: null,
          name: '',
          code: '',
          isDelete: 0,
          dataScope: null,
          aclIds: []
        })
      }
    },
    { immediate: true, deep: true }
)

const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}

const handleSubmit = async () => {
  try {
    loading.value = true
    await formRef.value.validate()

    // 准备提交的数据
    const submitData = {
      ...form,
      // 确保数字类型的字段正确转换
      dataScope: form.dataScope !== null ? Number(form.dataScope) : null,
      isDelete: Number(form.isDelete)
    }

    // 检查数据权限是否正确设置
    if (submitData.dataScope === null) {
      ElMessage.error('请选择数据权限')
      return
    }

    if (!submitData.id) {
      // 创建新角色
      await roleStore.createRole(submitData)
      ElMessage.success('角色创建成功')
    } else {
      // 更新现有角色
      await roleStore.updateRole(submitData)
      ElMessage.success('角色更新成功')
    }

    emit('success')
    handleClose()
  } catch (error) {
    if (error !== 'validate') {
      console.error('保存角色失败:', error)
      ElMessage.error('保存失败: ' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <el-dialog
      :model-value="visible"
      :title="form.id ? '编辑角色' : '新增角色'"
      width="500px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        v-loading="loading"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入角色名称" clearable />
      </el-form-item>

      <el-form-item label="角色编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入角色编码" clearable />
      </el-form-item>

      <el-form-item label="数据权限" prop="dataScope">
        <el-select
            v-model="form.dataScope"
            placeholder="请选择数据权限"
            style="width: 100%"
            clearable
        >
          <el-option label="全部数据" :value="1" />
          <el-option label="本部门" :value="2" />
          <el-option label="自定义" :value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="权限配置" prop="aclIds">
        <AclView v-model="form.aclIds" />
      </el-form-item>

      <el-form-item label="状态" v-if="form.id">
        <el-tag :type="form.isDelete === 0 ? 'success' : 'danger'">
          {{ form.isDelete === 0 ? '正常' : '已删除' }}
        </el-tag>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
            type="primary"
            @click="handleSubmit"
            :loading="loading"
            :disabled="form.isDelete === 1"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
